#include "widget.h"
#include "ui_widget.h"

#include <QTableWidgetItem>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 创建三行
    ui->tableWidget->insertRow(0);
    ui->tableWidget->insertRow(1);
    ui->tableWidget->insertRow(2);
    // 创建三列
    ui->tableWidget->insertColumn(0);
    ui->tableWidget->insertColumn(1);
    ui->tableWidget->insertColumn(2);
    // 给三列定列名
    ui->tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem("姓名"));
    ui->tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("学号"));
    ui->tableWidget->setHorizontalHeaderItem(2,new QTableWidgetItem("年龄"));

    // 初始化数据
    ui->tableWidget->setItem(0,0,new QTableWidgetItem("张三"));
    ui->tableWidget->setItem(0,1,new QTableWidgetItem("100"));
    ui->tableWidget->setItem(0,2,new QTableWidgetItem("21"));

    ui->tableWidget->setItem(1,0,new QTableWidgetItem("李四"));
    ui->tableWidget->setItem(1,1,new QTableWidgetItem("10"));
    ui->tableWidget->setItem(1,2,new QTableWidgetItem("2"));

    ui->tableWidget->setItem(2,0,new QTableWidgetItem("王五"));
    ui->tableWidget->setItem(2,1,new QTableWidgetItem("1005"));
    ui->tableWidget->setItem(2,2,new QTableWidgetItem("26"));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_insertRow_clicked()
{
    // 获取总行数
    int row = ui->tableWidget->rowCount();
    // 增加行
    ui->tableWidget->insertRow(row);
}


void Widget::on_pushButton_deleteRow_clicked()
{
    // 获取选中行
    int row = ui->tableWidget->currentRow();
    // 进行删除
    ui->tableWidget->removeRow(row);
}


void Widget::on_pushButton_insertColumn_clicked()
{
    // 获取一共多少列
    int column = ui->tableWidget->columnCount();
    // 添加列
    ui->tableWidget->insertColumn(column);
    // 设置列名
    // 列名从输入框获取
    const QString &text = ui->lineEdit->text();
    ui->tableWidget->setHorizontalHeaderItem(column,new QTableWidgetItem(text));
}


void Widget::on_pushButton_deleteColumn_clicked()
{
    // 获取选中列
    int column = ui->tableWidget->currentColumn();
    // 进行删除
    ui->tableWidget->removeColumn(column);
}

